import { defineStore } from 'pinia'
import axios from 'axios'

const DEFAULT_CUSTOMERS = [
  {
    id: 1,
    username: 'customer1',
    password: '123456', // 实际应用中应该加密存储
    phone: '13800138001',
    email: 'customer1@example.com',
    role: 'customer',
    createdAt: '2024-01-01T00:00:00.000Z'
  }
]

export const useCustomerStore = defineStore('customerStore', {
  state: () => ({
    customers: [],
    currentCustomer: null,
    initialized: false
  }),

  getters: {
    isLoggedIn: (state) => !!state.currentCustomer
  },

  actions: {
    initialize() {
      if (!this.initialized) {
        const storedCustomers = localStorage.getItem('customers')
        this.customers = storedCustomers ? JSON.parse(storedCustomers) : DEFAULT_CUSTOMERS
        if (!storedCustomers) {
          this.persist()
        }
        // 从localStorage恢复当前用户状态
        const storedCurrentCustomer = localStorage.getItem('currentCustomer')
        if (storedCurrentCustomer) {
          this.currentCustomer = JSON.parse(storedCurrentCustomer)
        }
        this.initialized = true
      }
    },

    async register(customerData) {
      // 检查用户名是否已存在
      if (this.customers.some(c => c.username === customerData.username)) {
        throw new Error('用户名已存在')
      }

      const newCustomer = {
        id: Date.now(),
        ...customerData,
        role: 'customer',
        createdAt: new Date().toISOString()
      }

      this.customers.push(newCustomer)
      this.persist()
      return newCustomer
    },

    async login(username, password) {
      // 确保store已初始化
      if (!this.initialized) {
        await this.initialize()
      }

      const customer = this.customers.find(
        c => c.username === username && c.password === password
      )
      
      if (!customer) {
        throw new Error('用户名或密码错误')
      }

      // 创建当前用户的副本，不包含密码
      const { password: _, ...customerWithoutPassword } = customer
      this.currentCustomer = { ...customerWithoutPassword, role: 'customer' }
      
      // 保存到localStorage
      localStorage.setItem('currentCustomer', JSON.stringify(this.currentCustomer))
      
      return this.currentCustomer
    },

    logout() {
      this.currentCustomer = null
      localStorage.removeItem('currentCustomer')
    },

    getCurrentCustomer() {
      if (!this.currentCustomer) {
        const stored = localStorage.getItem('currentCustomer')
        if (stored) {
          this.currentCustomer = JSON.parse(stored)
        }
      }
      return this.currentCustomer
    },

    persist() {
      localStorage.setItem('customers', JSON.stringify(this.customers))
    }
  }
})